<template>
    <el-dialog
          :model-value="visible"
          title="终端"
          @close="dialogClose"
          width="30%"
    >

     <el-form :model="form" ref="formRef" :rules="formRules" label-width="100px">
      <el-form-item label="SSH IP" prop="ssh_ip"> <!-- pod 名称输入框 -->
        <el-input v-model="form.ssh_ip" />
      </el-form-item>
      <el-form-item label="SSH 端口" prop="ssh_port"> <!-- pod 名称输入框 -->
        <el-input v-model="form.ssh_port" />
      </el-form-item>
      <el-form-item label="用户名" prop="ssh_username"> <!-- namespace 输入框 -->
        <el-input v-model="form.ssh_username" />
      </el-form-item>
      <el-form-item label="密码" prop="ssh_password"> <!-- pod 名称输入框 -->
        <el-input v-model="form.ssh_password"  show-password/>
      </el-form-item>
<!--        <div ref="xterm" /> &lt;!&ndash; 终端视图容器 &ndash;&gt;-->
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="onSubmit">连接</el-button>
        </span>
      </template>

  </el-dialog>

  <el-dialog
          :model-value="xtermvisible"
          width="60%"
          title="SSH终端"
          @close="xtermdialogClose"
          style="min-width: 1000px;"
          >
        <div class="host-info">
          <el-tag size="large" type="primary">用户名：{{xtermform.ssh_username}}</el-tag>
<!--          <el-tag size="large" type="success">主机名：{{xtermform.hostname}}</el-tag>-->
          <el-tag size="large" type="warning">IP地址：{{xtermform.ssh_ip}}</el-tag>
          <el-tag size="large" type="success">端口：{{xtermform.ssh_port}}</el-tag>
        </div>
        <div ref="xterm" class="terminal" style="height: 500px;margin-top: 20px"/>
     </el-dialog>
</template>

<script>
    import 'xterm/css/xterm.css'
    import { Terminal } from 'xterm'
    import { FitAddon } from 'xterm-addon-fit'  // xterm窗口自适应

    export default {
        name: "Terminal",
        props: {
            visible: Boolean,
            row: '',  // 当前行内容
        },
          data() {
            return {
              term: '',  // term实例
              ws: '', // ws连接
              form: {
                ssh_username: '',
                ssh_ip: '',
                ssh_port: '',
              },
              xtermform: {
                ssh_username: '',
                ssh_ip: '',
                ssh_port: '',
              },
              xtermvisible: false,
              formRules: {
                  ssh_username: [
                      {required: true, message: '请输入用户名', trigger: 'blur'},
                  ],
                  ssh_password: [
                      {required: true, message: '请输入密码', trigger: 'blur'},
                  ],
                  ssh_ip: [
                      {required: true, message: '请输入SSH IP地址', trigger: 'blur'},
                  ],
                  ssh_port: [
                      {required: true, message: '请输入SSH端口', trigger: 'blur'},
                  ],

                },
            }
          },
        methods: {
          onRest(){
            this.$refs.formRef.resetFields();
          },
           dialogClose() {
                this.$emit('update:visible', false);  // 当对话框关闭，通过父组件更新为false
                this.onRest(); //重置表单
                // window.location.reload();
              },
            onSubmit() {
               this.$refs.formRef.validate((valid) => {
                 if (valid) {
                   this.xtermform.ssh_username = this.form.ssh_username;
                   this.xtermform.ssh_ip = this.form.ssh_ip;
                   this.xtermform.ssh_port = this.form.ssh_port;
                   this.$emit('update:visible', false);
                   this.xtermvisible = true;
                   this.term = new Terminal({
                     fontSize: 18,
                     convertEol: true, // 启用时，光标将设置为下一行的开头
                     rendererType: 'canvas', // 渲染类型
                     cursorBlink: true, // 光标闪烁
                     cursorStyle: 'bar', // 光标样式 underline
                     theme: {
                       background: '#060101', // 背景色
                       cursor: 'help' // 设置光标
                     }
                   })
                   const fitPlugin = new FitAddon()
                   fitPlugin.activate(this.term)
                   // this.term.loadAddon(fitPlugin)

                   // 建立ws连接
                   this.ws = new WebSocket(`ws://${process.env.VUE_APP_API_HOST}:${process.env.VUE_APP_API_PORT}/server/terminal/${this.form.ssh_ip}/${this.form.ssh_port}/${this.form.ssh_username}/${this.form.ssh_password}/`)

                   // 建立ws连接成功后回调
                   this.ws.onopen = () => {
                     // 将term挂载到标签上
                     this.term.open(this.$refs.xterm)
                     this.term.focus()
                     fitPlugin.fit()
                   }

                   // 获取后端传回的数据
                   this.ws.onmessage = (res) => {
                     const reader = new window.FileReader()
                     reader.onload = () => this.term.write(reader.result)
                     reader.readAsText(res.data, 'utf-8')
                   }

                   // 用户输入发送到后端
                   this.term.onData(data => this.ws.send(JSON.stringify({data})))

                   // 动态设置终端窗口大小
                   this.term.onResize(({cols, rows}) => {
                     this.ws.send(JSON.stringify({resize: [cols, rows]}))
                   })
                   window.onresize = () => fitPlugin.fit()

                   // ws关闭连接
                   this.ws.onclose = (e) => {
                     console.log('Websocket关闭：' + e)
                     // this.cleanupSocket();
                   }
                 }else {
                   this.$message.error('格式错误！')
                 }
               })
            },
           //清理websocket和终端资源
           cleanupSocket(){
              if (this.ws){
                this.ws.close();
              }
              if (this.term){
                this.term.dispose();
              }
            },
           xtermdialogClose() {
              this.cleanupSocket();
              this.xtermvisible = false;  // 父组件必须使用v-model
              window.location.reload()
            },
        }
    }
</script>

<style scoped>

</style>